import React, { Component } from "react";
import { Popover, Icon } from "antd";
import TweenOne from "rc-tween-one";
import Children from "rc-tween-one/lib/plugin/ChildrenPlugin";
import moment from "moment";
import "styles/dashboard/staff-info-box.scss";
import { messages, eventTrack } from "share/common";
import constants from "share/constants";
import { connect } from "react-redux";
import UserMale from "images/user-male.png";
import UserFemale from "images/user-female.png";
import UserUnknown from "images/user-unknow.png";
import dashboardService from "containers/dashboard/dashboard.service";
import menuRoute from "routes/menuRoute";

TweenOne.plugins.push(Children);

const showMap = [
  {
    key: "reimbursed",
    name: messages("basic-1.key231") /*待报销*/,
    type: "amount",
    animationName: "animationReimbursed",
    menuKey: "my-account",
    targetName: messages("basic-1.key97") /*账本*/,
  },
  {
    key: "borrow",
    name: messages("basic-1.key114") /*待还款*/,
    type: "amount",
    animationName: "animationBorrow",
    menuKey: "borrow-management",
    targetName: messages("basic-1.key114") /*待还款*/,
  },
  {
    key: "pending",
    name: messages("basic-1.key232") /*待审批*/,
    type: "count",
    animationName: "animationPending",
    menuKey: "approve",
    targetName: messages("basic-1.key232") /*待审批*/,
  },
];

class ShowStaffInfo extends Component {
  constructor(props) {
    super(props);
    this.state = {
      target: "", //上午下午晚上
      tip: "", //鸡汤
      animationReimbursed: null,
      animationBorrow: null,
      animationPending: null,
      animationReimbursedData: 0,
      animationBorrowData: 0,
      animationPendingData: 0,
      animationReimbursedCurrency: "-",
      animationBorrowCurrency: "-",
      animationPendingCurrency: "-",
    };
    this.userImg = {
      0: UserMale,
      1: UserFemale,
      2: UserUnknown,
    };
  }

  componentWillMount() {
    this.getPersonalInfo();
    this.getIndexDetail();
  }

  componentDidMount() {}

  componentWillReceiveProps(nextProps, nextContext) {}

  getIndexDetail = () => {
    dashboardService.getWaitForApprove({ isAll: true }).then((res) => {
      if (res.status === 200) {
        const result = res.data.find((item) => item.entityType === "total");
        this.trigger(result.count, "", "animationPending", false);
      }
    });
    dashboardService.getAccountBook().then((res) => {
      if (res.status === 200) {
        this.trigger(res.data.totalAmount, res.data.baseCurrency, "animationReimbursed");
      }
    });
    dashboardService.getWaitForPay().then((res) => {
      if (res.status === 200) {
        this.trigger(res.data.stayWriteOffAmount, res.data.currencyCode, "animationBorrow");
      }
    });
  };

  //获取个人信息板块详情，包括个人信息，当前时间，鸡汤
  getPersonalInfo = () => {
    const hour = moment().hour();
    let target = "";
    if (hour < 4) {
      target = "night";
    } else if (hour < 12) {
      target = "am";
    } else if (hour < 18) {
      target = "pm";
    } else {
      target = "night";
    }
    this.setState({
      target:
        target === "night"
          ? messages("basic-1.key131") /*晚上好*/
          : target === "am"
          ? messages("basic-1.key132") /*上午好*/
          : messages("basic-1.key133") /*下午好*/,
      tip: constants.dashboardTips[target][Math.floor(Math.random() * constants.dashboardTips[target].length)],
      loginUser: this.props.loginUser,
    });
  };

  trigger = (value, currencyCode, animationName, needFloat = true) => {
    const obj = {};
    obj[animationName] = {
      Children: {
        value: typeof value === "number" ? value : 0,
        floatLength: needFloat ? 2 : 0,
        formatMoney: true,
      },
      duration: 1000,
    };
    obj[`${animationName}Data`] = value;
    obj[`${animationName}Currency`] = currencyCode || "-";
    this.setState(obj);
  };

  handleJump = (item) => {
    this.context.router.push(menuRoute.getRouteItem(item.menuKey).url);
    eventTrack({
      category: "1218-新首页-埋点",
      action: `通过点击个人首页${item.name}进入了${item.targetName}`,
      label: this.props.tenant.tenantName,
    });
  };

  render() {
    const { language, loginUser, menuTree } = this.props;
    const { target, tip } = this.state;
    const arr = (loginUser.departmentName || "").split("|");
    const url = menuTree.keyUrl["borrow-management"];
    const myAccountUrl = menuTree.keyUrl["my-account"];
    const approveUrl = menuTree.keyUrl.approve;

    const node = (
      <span className={"user-name-department"}>
        {loginUser.title}
        {arr.length ? ` | ${arr[arr.length - 1]}` : ""}
      </span>
    );

    return (
      <div className="staff-info-box">
        <div className="personal-info">
          <div className="user-img-box">
            <img className="user-img" src={loginUser.filePath || this.userImg[loginUser.gender]} />
          </div>
          <div className="right-user-content">
            <div className="hello">{`${target}, ${loginUser.fullName}`}</div>
            <Popover placement={"topLeft"} content={node}>
              {node}
            </Popover>
            {language.code === "zh_cn" && <div className="dashboard-tip">"{tip}"</div>}
          </div>
        </div>
        <div className="staff-index-box">
          {showMap.map((item) => {
            if (item.key === "borrow" && !url) {
              return <span />;
            } else if (item.key === "reimbursed" && !myAccountUrl) {
              return <span />;
            } else if (item.key === "pending" && !approveUrl) {
              return <span />;
            }
            return (
              <div
                className="staff-index-single"
                onClick={() => {
                  this.handleJump(item);
                }}
              >
                <div className="name-and-currency">
                  <span className="name">{item.name}</span>
                  {item.type === "amount" && (
                    <span className="currency">({this.state[`${item.animationName}Currency`]})</span>
                  )}
                </div>
                <div className="need-right">
                  {this.state[`${item.animationName}Data`] < 1000000000 ? (
                    <TweenOne
                      animation={this.state[item.animationName]}
                      className={`number ${!this.state[`${item.animationName}Data`] ? "null" : ""}`}
                    >
                      0
                    </TweenOne>
                  ) : (
                    <span className={"number"}>
                      {this.filterMoney(this.state[`${item.animationName}Data`], 2, true)}
                    </span>
                  )}
                  {item.type === "count" && <Icon className={"number-triangle"} type="right" />}
                </div>
              </div>
            );
          })}
        </div>
      </div>
    );
  }
}

ShowStaffInfo.propTypes = {};

ShowStaffInfo.contextTypes = {
  router: React.PropTypes.object,
};

function mapStateToProps(state) {
  return {
    loginUser: state.login.loginUser,
    language: state.main.language,
    menuTree: state.login.menuTree,
    profile: state.login.profile,
  };
}

export default connect(mapStateToProps)(ShowStaffInfo);
